using HttpServer.Models;
using Microsoft.AspNetCore.Mvc;
using MySql.Data.MySqlClient;


namespace HttpServer.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class PlayerSignInfoController : ControllerBase
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpPost("UserSignInfo")]
        public IActionResult UserSignInfo([FromQuery] string userId)
        {
            return StatusCode(400, "Error");
        }

        /// <summary>
        /// 获取签到数据
        /// </summary>
        /// <param name="id"></param>
        /// <param name="year"></param>
        /// <returns></returns>
        [HttpGet("GetSignInfo/{id}:{year}")]
        public ActionResult<UserSignInfo> GetSignInfo(int id, int year)
        {
            try
            {
                using MySqlConnection connection =
                    new MySqlConnection(SqlLinkManager.sqlConnectionCommand);
                connection.Open();
                string query = $"SELECT * FROM usersigninfo WHERE UserId = {id} AND Year = {year}";
                using MySqlCommand command = new MySqlCommand(query, connection);

                MySqlDataReader dr = command.ExecuteReader();
                UserSignInfo info = new UserSignInfo();
                if (dr.Read())
                {
                    info.UserId = dr["UserId"] == DBNull.Value ? -1 : (int)dr["UserId"];
                    info.Year = (int)dr["Year"];
                    info.SignInBits1 = (int)dr["SignInBits1"];
                    info.SignInBits2 = (int)dr["SignInBits2"];
                    info.SignInBits3 = (int)dr["SignInBits3"];
                    info.SignInBits4 = (int)dr["SignInBits4"];
                    info.SignInBits5 = (int)dr["SignInBits5"];
                    info.SignInBits6 = (int)dr["SignInBits6"];
                    info.SignInBits7 = (int)dr["SignInBits7"];
                    info.SignInBits8 = (int)dr["SignInBits8"];
                    info.SignInBits9 = (int)dr["SignInBits9"];
                    info.SignInBits10 = (int)dr["SignInBits10"];
                    info.SignInBits11 = (int)dr["SignInBits11"];
                    info.SignInBits12 = (int)dr["SignInBits12"];
                    return StatusCode(200,new RequestData(200,"获取玩家签到数据", info));
                }
                else
                {
                    return StatusCode(200,new RequestData(200,"签到数据获取失败", info));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return StatusCode(400, "Error");
            }
        }


        /// <summary>
        /// 玩家签到
        /// </summary>
        /// <returns></returns>
        [HttpPost("PlayerDailySignIn")]
        public IActionResult PlayerDailySignIn(int id)
        {
            try
            {
                using (MySqlConnection connection =
                       new MySqlConnection(SqlLinkManager.sqlConnectionCommand))
                {
                    connection.Open();
                    string query =
                        $"SELECT * FROM usersigninfo WHERE UserId = {id} AND Year = {DateTime.Now.Year}";
                    UserSignInfo info = new UserSignInfo
                    {
                        UserId = id,
                        Year = DateTime.Now.Year,
                    };
                    using (MySqlCommand command = new MySqlCommand(query, connection))
                    using (MySqlDataReader dr = command.ExecuteReader())
                    {
                        //查询数据库是否有数据
                        if (dr.Read())
                        {
                            //有数据
                            info.UserId = dr["UserId"] == DBNull.Value ? -1 : (int)dr["UserId"];
                            info.Year = (int)dr["Year"];
                            info.SignInBits1 = (int)dr["SignInBits1"];
                            info.SignInBits2 = (int)dr["SignInBits2"];
                            info.SignInBits3 = (int)dr["SignInBits3"];
                            info.SignInBits4 = (int)dr["SignInBits4"];
                            info.SignInBits5 = (int)dr["SignInBits5"];
                            info.SignInBits6 = (int)dr["SignInBits6"];
                            info.SignInBits7 = (int)dr["SignInBits7"];
                            info.SignInBits8 = (int)dr["SignInBits8"];
                            info.SignInBits9 = (int)dr["SignInBits9"];
                            info.SignInBits10 = (int)dr["SignInBits10"];
                            info.SignInBits11 = (int)dr["SignInBits11"];
                            info.SignInBits12 = (int)dr["SignInBits12"];
                        }
                    }

                    SignIn(DateTime.Now.Month,DateTime.Now.Day, info);

                    // 使用 INSERT ... ON DUPLICATE KEY UPDATE 语句
                    string insertOrUpdateQuery = @"
                        INSERT INTO usersigninfo (UserId, Year, SignInBits1, SignInBits2, SignInBits3, SignInBits4, SignInBits5, SignInBits6, SignInBits7, SignInBits8, SignInBits9, SignInBits10, SignInBits11, SignInBits12) 
                        VALUES (@UserId, @Year, @SignInBits1, @SignInBits2, @SignInBits3, @SignInBits4, @SignInBits5, @SignInBits6, @SignInBits7, @SignInBits8, @SignInBits9, @SignInBits10, @SignInBits11, @SignInBits12)
                        ON DUPLICATE KEY UPDATE 
                            SignInBits1 = VALUES(SignInBits1), 
                            SignInBits2 = VALUES(SignInBits2), 
                            SignInBits3 = VALUES(SignInBits3), 
                            SignInBits4 = VALUES(SignInBits4), 
                            SignInBits5 = VALUES(SignInBits5), 
                            SignInBits6 = VALUES(SignInBits6),
                            SignInBits7 = VALUES(SignInBits7),
                            SignInBits8 = VALUES(SignInBits8),
                            SignInBits9 = VALUES(SignInBits9),
                            SignInBits10 = VALUES(SignInBits10),
                            SignInBits11 = VALUES(SignInBits11),
                            SignInBits12 = VALUES(SignInBits12)";

                    using (MySqlCommand insertCommand =
                           new MySqlCommand(insertOrUpdateQuery, connection))
                    {
                        insertCommand.Parameters.AddWithValue("@UserId", info.UserId);
                        insertCommand.Parameters.AddWithValue("@Year", info.Year);
                        insertCommand.Parameters.AddWithValue("@SignInBits1", info.SignInBits1);
                        insertCommand.Parameters.AddWithValue("@SignInBits2", info.SignInBits2);
                        insertCommand.Parameters.AddWithValue("@SignInBits3", info.SignInBits3);
                        insertCommand.Parameters.AddWithValue("@SignInBits4", info.SignInBits4);
                        insertCommand.Parameters.AddWithValue("@SignInBits5", info.SignInBits5);
                        insertCommand.Parameters.AddWithValue("@SignInBits6", info.SignInBits6);
                        insertCommand.Parameters.AddWithValue("@SignInBits7", info.SignInBits7);
                        insertCommand.Parameters.AddWithValue("@SignInBits8", info.SignInBits8);
                        insertCommand.Parameters.AddWithValue("@SignInBits9", info.SignInBits9);
                        insertCommand.Parameters.AddWithValue("@SignInBits10", info.SignInBits10);
                        insertCommand.Parameters.AddWithValue("@SignInBits11", info.SignInBits11);
                        insertCommand.Parameters.AddWithValue("@SignInBits12", info.SignInBits12);

                        int returnIndex = insertCommand.ExecuteNonQuery();
                        if (returnIndex > 0)
                        {
                            Console.WriteLine("签到成功");
                            return StatusCode(200,new RequestData(200,"签到成功"));
                        }
                    }

                }
            }
            catch (MySqlException e)
            {
                // 提取错误信息
                string errorMessage = e.Message;
                int errorCode = e.Number; // 获取 MySQL 错误代码

                // 处理特定错误代码
                switch (errorCode)
                {
                    case 1452: // 外键约束错误
                        return StatusCode(200,new RequestData(400,$"签到失败：用户ID不存在 ID: {id}"));
                    case 1062: // 唯一键冲突
                        return StatusCode(200,new RequestData(400,"签到失败：重复签到"));
                    default:
                        return StatusCode(200,new RequestData(400,$"签到失败：{errorMessage}"));
                }
            }

            return StatusCode(400, "Error");
        }

        private void SignIn(int month, int day, UserSignInfo info)
        {
            // 1. 确保月份在 1-12 之间
            if (month < 1 || month > 12) return;

            // 2. 确保天数在合法范围内（每个月最多 31 天）
            if (day < 1 || day > 31) return;

            // 3. 计算签到位（0 开始的索引）
            int bitPosition = day - 1;

            // 4. 直接修改 `info` 的对应月份
            switch (month)
            {
                case 1: info.SignInBits1 |= (1 << bitPosition); break;
                case 2: info.SignInBits2 |= (1 << bitPosition); break;
                case 3: info.SignInBits3 |= (1 << bitPosition); break;
                case 4: info.SignInBits4 |= (1 << bitPosition); break;
                case 5: info.SignInBits5 |= (1 << bitPosition); break;
                case 6: info.SignInBits6 |= (1 << bitPosition); break;
                case 7: info.SignInBits7 |= (1 << bitPosition); break;
                case 8: info.SignInBits8 |= (1 << bitPosition); break;
                case 9: info.SignInBits9 |= (1 << bitPosition); break;
                case 10: info.SignInBits10 |= (1 << bitPosition); break;
                case 11: info.SignInBits11 |= (1 << bitPosition); break;
                case 12: info.SignInBits12 |= (1 << bitPosition); break;
            }
        }
    }
}

